<template>
  <div>
    <el-tree
      ref="refTree"
      :data="permissionData"
      :props="{ label: 'name' }"
      :default-expand-all="true"
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <el-button type="primary" @click="hSave">确认</el-button>
    <el-button @click="hCancel">取消</el-button>
  </div>

</template>
<script>
import { getRoleDetail, assignPerm } from '@/api/settings'
// 获取所以权限信息
import { getPermissionList } from '@/api/permission'
// 导入数组转树
import { array2Tree } from '@/utils/index'

export default ({
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: []
    }
  },
  created() {
    // 调用接口，获取所有的权限点数据
    this.loadPermissionList()
    // 调用接口，获取当前这个角色已经具备的权限
    this.loadPermissionByRoleId()
  },
  methods: {
  // 点击取消
    hCancel() {
      this.$emit('close')
      // 清空当前的选择
      this.$refs.refTree.setCheckedKeys([])
    },
    // 获取所有权限信息
    async loadPermissionList() {
      const res = await getPermissionList()
      console.log('权限信息', res)
      this.permissionData = array2Tree(res.data, '0')
    },
    async loadPermissionByRoleId() {
    // 根据roleId获取当前这个角色已经具备的权限
      const res = await getRoleDetail(this.id)
      console.log('获取当前角色的已有的权限点数据', res.data.permIds)
      // 回填
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    },
    async hSave() {
      const permIds = this.$refs.refTree.getCheckedKeys()
      // console.log('当前选中的节点数组是', permIds)
      await assignPerm({
        id: this.id,
        permIds: permIds
      })
      // 提示
      this.$message.success('保存角色的权限成功')
      // 关闭弹层
      this.hCancel()
    }
  }
})
</script>

